package com.yoyo.yyadsdk.serv;

import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.pm.ShortcutInfoCompat;
import androidx.core.content.pm.ShortcutManagerCompat;
import androidx.core.graphics.drawable.IconCompat;

import com.anye.greendao.gen.DaoSession;
import com.anye.greendao.gen.LocalShortcutEntityDao;
import com.anye.greendao.gen.ShortcutEntityDao;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.dollkey.hdownload.activity.AdWebViewActivity;
import com.yoyo.ad.utils.StringUtil;
import com.yoyo.yyadsdk.BuildConfig;
import com.yoyo.yyadsdk.R;
import com.yoyo.yyadsdk.bean.dao.ConfigEntity;
import com.yoyo.yyadsdk.bean.dao.LocalShortcutEntity;
import com.yoyo.yyadsdk.bean.dao.RuleListEntity;
import com.yoyo.yyadsdk.bean.dao.ShortcutEntity;
import com.yoyo.yyadsdk.broad.ShortCutCallbackReceiver;
import com.yoyo.yyadsdk.config.Constants;
import com.yoyo.yyadsdk.config.PullFeature;
import com.yoyo.yyadsdk.demo.DBManager;
import com.yoyo.yyadsdk.util.AlarmUtils;
import com.yoyo.yyadsdk.util.GreenDaoManager;
import com.yoyo.yyadsdk.util.ShortcutUtil;
import com.yoyo.yyadsdk.util.TimeUtils;

import java.util.ArrayList;
import java.util.List;

public class AddShortCutService extends IntentService {
    private List<String> names;
    private String name;

    public AddShortCutService() {
        super("AddShortCutService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        DaoSession daoSession = GreenDaoManager.getInstance().getDaoSession();
        ShortcutEntityDao shortcutEntityDao = daoSession.getShortcutEntityDao();
        long currentTimeMillis = System.currentTimeMillis();
        //获取有效期内的数据
        List<ShortcutEntity> list = shortcutEntityDao.queryBuilder().where(ShortcutEntityDao.Properties.StartTime.le(currentTimeMillis),
                ShortcutEntityDao.Properties.EndTime.gt(currentTimeMillis)).list();
        List<Integer> ids = new ArrayList<>();
        //获取快捷方式id集
        for (ShortcutEntity s : list) {
            ids.add(s.getId());
        }
        long dayTime = TimeUtils.getDay();
        //获取今天内创建的快捷方式
        List<LocalShortcutEntity> localShortcutEntities = daoSession.getLocalShortcutEntityDao().queryBuilder()
                .where(LocalShortcutEntityDao.Properties.ShortcutId.in(ids),
                        LocalShortcutEntityDao.Properties.IsDel.eq(false),
                        LocalShortcutEntityDao.Properties.LastClickTime.eq(dayTime)).list();
        List<RuleListEntity> ruleListEntityList = daoSession.getRuleListEntityDao().queryBuilder().list();
        //获取符合条件的快捷方式
        List<ShortcutEntity> tempList = new ArrayList<>();
        for (ShortcutEntity s : list) {
            LocalShortcutEntity localShortcutEntity = null;
            for (LocalShortcutEntity l : localShortcutEntities) {
                if (l.getShortcutId() == s.getId()) {
                    localShortcutEntity = l;
                    break;
                }
            }
            if (localShortcutEntity != null) {
                if (localShortcutEntity.getClickCount() >= s.getFrequency()) {
                    //周期内达到点击次数阈值，删除
                    AlarmUtils.addTask(PullFeature.ALARM_DEL_SHORT_CUT, s.getTitle().concat(",").concat(String.valueOf(s.getId())),
                            0, false, 0);
                    continue;
                }
            }
            //判断黑白名单
            RuleListEntity r = null;
            for (RuleListEntity ruleListEntity : ruleListEntityList)
                if (s.getRuleId() == ruleListEntity.getRuleId()) {
                    r = ruleListEntity;
                    break;
                }
            if (r != null) {
                if (r.getType() == PullFeature.PULL_WHITE_LIST) {
                    //白名单
                    if (!r.getInWhiteRule()) {
                        continue;
                    }
                } else {
                    //黑名单
                    if (r.getInBlackRule()) {
                        continue;
                    }
                }
            }
            tempList.add(s);
        }
        getHomePackageName(this);
//        int count = getShortcutCount(this);
        int count = (int) daoSession.getLocalShortcutEntityDao().queryBuilder()
                .where(LocalShortcutEntityDao.Properties.IsDel.eq(false)).count();
        ConfigEntity configEntity = Constants.getConfigEntity();
        int maxCount = 0;
        if (configEntity != null) {
            maxCount = configEntity.getShortcutMaxCount();
        }
        int size = Math.min(tempList.size(), maxCount - count);
        List<LocalShortcutEntity> saveLocalShortcuts = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            ShortcutEntity shortcutEntity = tempList.get(i);
            int _count = getShortcutCount(this, shortcutEntity.getTitle());
            if (_count > 0) {
                continue;
            }
            addShortCutCompact(this, shortcutEntity.getId(), shortcutEntity.getUrl(), shortcutEntity.getTitle(), shortcutEntity.getIcon());

            //设置删除快捷方式闹钟
            long time = TimeUtils.DAY;
            long diff = shortcutEntity.getEndTime() - currentTimeMillis;
            time = Math.min(diff, time);
            if (time <= 0) {
                time = 0;
            }
            AlarmUtils.addTask(PullFeature.ALARM_DEL_SHORT_CUT, shortcutEntity.getTitle().concat(",").concat(String.valueOf(shortcutEntity.getId())),
                    time, false, 0);

            //记录本地记录数据
            LocalShortcutEntity l = null;
            for (LocalShortcutEntity lse : localShortcutEntities) {
                if (lse.getShortcutId() == shortcutEntity.getId()) {
                    l = lse;
                    l.setClickCount(lse.getClickCount() + 1);
                    break;
                }
            }
            if (l == null) {
                l = new LocalShortcutEntity();
                l.setShortcutId(shortcutEntity.getId());
                l.setClickCount(1);
                l.setIsDel(false);
            }
            l.setLastClickTime(dayTime);
            saveLocalShortcuts.add(l);
        }
        daoSession.getLocalShortcutEntityDao().insertOrReplaceInTx(saveLocalShortcuts);
    }

    public static void addShortCutCompact(final Context context, final int id, final String url, final String name, String iconUrl) {
        if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
            Glide.with(context).asBitmap().load(iconUrl).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                    if (Build.VERSION.SDK_INT < 25) {
                        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
                        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
                        shortcut.putExtra("duplicate", false);// 设置是否重复创建
                        Intent intent = AdWebViewActivity.newIntent(context, url);
                        intent.putExtra("shortcut", id);
                        intent.setAction("com.dollkey.hdownload.MAIN"); //action必须设置，不然报错
//                    intent.setAction(Intent.ACTION_MAIN); //action必须设置，不然报错
                        intent.addCategory(Intent.CATEGORY_LAUNCHER);
                        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
                        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON, resource);
                        context.sendBroadcast(shortcut);
                    } else {
                        Intent shortcutInfoIntent = AdWebViewActivity.newIntent(context, url);
                        shortcutInfoIntent.setAction("com.dollkey.hdownload.MAIN"); //action必须设置，不然报错
                        shortcutInfoIntent.putExtra("duplicate", false);
                        shortcutInfoIntent.putExtra("shortcut", id);
                        ShortcutInfoCompat info = new ShortcutInfoCompat.Builder(context, "com.yoyo.shortcut" + id)
                                .setIcon(IconCompat.createWithBitmap(resource))
                                .setShortLabel(name)
                                .setIntent(shortcutInfoIntent)
                                .build();
                        //当添加快捷方式的确认弹框弹出来时，将被回调
                        PendingIntent shortcutCallbackIntent = PendingIntent.getBroadcast(context, 0,
                                new Intent(context, ShortCutCallbackReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
                        ShortcutManagerCompat.requestPinShortcut(context, info, shortcutCallbackIntent.getIntentSender());
                    }
                }
            });
        }
    }

    public int getShortcutCount(Context context, String title) {
        int count = 0;
//        String title = "支付宝";
        String uri = Build.VERSION.SDK_INT < 19 ? "content://com.android.launcher2.settings/favorites?notify=true"
                : "content://com.android.launcher3.settings/favorites?notify=true";
        String uriStr = StringUtil.isNull(name) ? uri : "content://".concat(name).concat(".settings/favorites?notify=true");
        final Uri CONTENT_URI = Uri.parse(uriStr);
//        final Cursor c = context.getContentResolver().query(CONTENT_URI, null, null, null, null);
        final Cursor c = context.getContentResolver().query(CONTENT_URI, null, "title=?", new String[]{title}, null);
        if (c != null) {
            if (c.getCount() > 0)
                count = c.getCount();
            c.close();
        }
        return count;
    }

    private List<String> getHomePackageName(Context context) {
        if (names == null) {
            names = new ArrayList<>();
            PackageManager packageManager = context.getPackageManager();
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo ri : resolveInfo) {
                names.add(ri.activityInfo.packageName);
                if (ri.activityInfo.packageName.contains("launcher")) {
                    name = ri.activityInfo.packageName;
                }
            }
        }
        return names;
    }
}
